package com.czl.module_service.fragment.inventory

import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.event.LiveBusCenter
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.adapter.inventory.InventoryChildAdapter
import com.czl.module_service.viewmodel.inventory.InventoryChildViewModel
import android.view.Gravity

import androidx.core.widget.PopupWindowCompat

import com.blankj.utilcode.util.SizeUtils

import android.graphics.drawable.ColorDrawable

import android.view.ViewGroup

import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater

import android.widget.TextView

import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.czl.base.data.bean.tengyun.FileBean
import com.czl.base.data.bean.tengyun.InventoryAssetBean
import com.czl.base.util.ChoiceImgHelper
import com.czl.base.util.ToastHelper
import com.czl.module_service.adapter.PurchaseApplyAdapter
import com.czl.module_service.databinding.*
import com.czl.module_service.extension.loadCompletedData
import com.czl.module_service.view.BaseCenterPopup
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView


/**
 * @author by xubin
 * PS: Not easy to write code, please indicate.
 */
@Route(path = AppConstants.Router.Service.F_SERVICE_ASSET_INVENTORY_CHILD)
class InventoryChildFragment :
    BaseFragment<FragmentInventoryChildBinding, InventoryChildViewModel>() {

    var loaded: Boolean = false

    // 盘点任务状态
    var status : Int? = null

    // 当前操作的tab
    var tabIndex : Int? = null

    // 当前操作的对象
    var data: InventoryAssetBean = InventoryAssetBean()

    var productList: MutableList<InventoryAssetBean> = arrayListOf()

    private val headerBinding: FragmentInventoryChildHeaderBinding by lazy {
        FragmentInventoryChildHeaderBinding.inflate(layoutInflater).apply {

        }
    }

    private val mAdapter: InventoryChildAdapter by lazy {
        InventoryChildAdapter(this).apply {
            headerBinding.setVariable(initVariableId(), viewModel)
            addHeaderView(headerBinding.root)
        }
    }

    override fun initContentView(): Int {
        return R.layout.fragment_inventory_child
    }

    override fun initData() {
        super.initData()
        viewModel.execId = arguments?.getString("execId")
        viewModel.taskId = arguments?.getLong("taskId")
        viewModel.tabIndex = arguments?.getInt("tabIndex")
        tabIndex = arguments?.getInt("tabIndex")
        status = arguments?.getInt("status")
        if (status != 1) {
            headerBinding.linearlayout.visibility = View.VISIBLE
            binding.llBtn.visibility = View.VISIBLE
        } else {
            headerBinding.linearlayout.visibility = View.GONE
            binding.llBtn.visibility = View.GONE
        }
        initAdapter()
        reload()
    }

    override fun onResume() {
        super.onResume()
        loadData()
    }

    private fun loadData() {
        if (!loaded) {
            reload()
        }
    }

    private fun initAdapter() {
        binding.ryCommon.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            adapter = mAdapter
        }
    }

    override fun useBaseLayout(): Boolean {
        return false
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun reload() {
        super.reload()
        binding.smartCommon.autoRefresh()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        LiveBusCenter.observeScanResultReturnEvent(this, {
            // 扫码结果返回
            viewModel.markPosition = -1
            if (it.result == null || it.result!!.isEmpty()) {
                showNormalToast("无法获取资产信息!")
            } else {
                if (it.result == viewModel.lastScanCode) {
                    showNormalToast("该资产已盘点!")
                } else {
                    viewModel.markPosition = 0
                    viewModel.lastScanCode = it.result
                    viewModel.getFacilityByNo(it.result)
                }
            }
        })
        LiveBusCenter.observeSearchParamReturnEvent(this, {
            // 点击搜索查询
            viewModel.titleName = it.param
            viewModel.wechatGetTaskFacilityInfoByTaskId(tabIndex)
        })
        LiveBusCenter.observeUploadImgReturnEvent(this, {
            // 拍照盘点
            viewModel.markPosition = 0
            toSubstitute(data, 1, "", 0, null, 0, viewModel.imgList)
        })
        viewModel.uc.loadArtificialShowPopEvent.observe(this) {
            if (it != null)
                artificial(it)
        }
        viewModel.uc.loadCompleteEvent.observe(this) { data ->
            showSuccessStatePage()
            productList = (data?.list as MutableList<InventoryAssetBean>?)!!
            if (data != null) {
                if (tabIndex == 0 && status != 1 && data.list?.size!! > 0) {
                    binding.btnCommit.isEnabled = false
                    binding.btnCommit.setTextColor(ContextCompat.getColor(requireContext(), R.color.gray))
                }
                this.loadCompletedData(
                    data.hasNextPage,
                    viewModel.currentPage == 2,
                    data != null,
                    data.total,
                    data.list,
                    mAdapter,
                    binding.ryCommon,
                    binding.smartCommon
                )
//                data.list?.let { mAdapter.setList(it) }
            }
            if (!mAdapter.hasEmptyView() && !mAdapter.hasHeaderLayout()) {
                val emptyView =
                    View.inflate(context, com.czl.base.R.layout.common_empty_layout, null)
                mAdapter.setEmptyView(emptyView)
            }
        }
        viewModel.uc.loadSuccessEvent.observe(this) {
            if (it == 1000) {
                binding.btnCommit.isEnabled = false
                binding.btnCommit.setTextColor(ContextCompat.getColor(requireContext(), R.color.gray))
                LiveBusCenter.postAssetResultReturnEvent(1)
                back()
            } else {
                if (it == 100) {
                    val list = mAdapter.data
                    var inventoryAssetBean : InventoryAssetBean? = null
                    if (list.size > 0) {
                        list.forEach { t ->
                            if (t.taskId == viewModel.scanData.taskId) {
                                inventoryAssetBean = t
                            }
                        }
                    }
                    if (inventoryAssetBean != null) {
                        mAdapter.remove(inventoryAssetBean!!)
                    }

                } else {
                    if (!((tabIndex == 1 && viewModel.markPosition == 0) || (tabIndex == 3 && viewModel.markPosition == 2) || viewModel.markPosition == -1 || viewModel.markPosition == 4 )) {
                        mAdapter.remove(data)
                    }
                }
                val list = mAdapter.data
                LiveBusCenter.postInventoryResultReturnEvent(tabIndex, viewModel.markPosition)
                if (tabIndex == 0 && status != 1 && list.size == 0) {
                    binding.btnCommit.isEnabled = true
                    binding.btnCommit.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
                }
                if (viewModel.markPosition == -1) {
                    reload()
                }
            }
            LiveBusCenter.postInventoryHomeReturnEvent(1)
        }
        viewModel.uc.loadFinallyEvent.observe(this, {
            loaded = true
            binding.smartCommon.finishRefresh()
        })
    }

    fun showMenu(bean: InventoryAssetBean, anchor: View) {
        data = bean
        viewModel.markPosition = -1
        val window = PopupWindow(context)
        val view: View = View.inflate(context, R.layout.menu_add_inventory, null)
        val tvTitle1 = view.findViewById<TextView>(R.id.tv_menu_title1)
        val tvTitle2 = view.findViewById<TextView>(R.id.tv_menu_title2)
        val tvTitle3 = view.findViewById<TextView>(R.id.tv_menu_title3)
        val tvTitle4 = view.findViewById<TextView>(R.id.tv_menu_title4)
        val tvTitle5 = view.findViewById<TextView>(R.id.tv_menu_title5)
        if (tabIndex == 0 && bean.inventoryType == 0) {
            if (bean.isCheck == 0 && status != 1) {
                tvTitle1.visibility = View.VISIBLE
                tvTitle2.visibility = View.VISIBLE
                tvTitle5.visibility = View.VISIBLE
                tvTitle1.text = "人工盘点"
                tvTitle5.text = "拍照盘点"
            }
            tvTitle3.visibility = View.VISIBLE
            tvTitle4.visibility = View.GONE
        } else if ((tabIndex == 1 || tabIndex == 3) && bean.inventoryType == 0) {
            if ( status != 1) {
                tvTitle1.visibility = View.VISIBLE
                tvTitle5.visibility = View.VISIBLE
                tvTitle1.text = "人工重盘"
                tvTitle5.text = "拍照重盘"
            }
            tvTitle2.visibility = View.GONE
            tvTitle3.visibility = View.VISIBLE
            tvTitle4.visibility = View.GONE
        } else if (bean.inventoryType == 1 && tabIndex == 0) {
            if (bean.isCheck == 0 && status != 1) {
                tvTitle2.visibility = View.VISIBLE
            }
            tvTitle1.visibility = View.GONE
            tvTitle3.visibility = View.VISIBLE
            tvTitle4.visibility = View.GONE
            tvTitle5.visibility = View.GONE
        } else if (bean.inventoryType == 2 && tabIndex == 0) {
            if (bean.isCheck == 0 && status != 1) {
                tvTitle1.visibility = View.VISIBLE
                tvTitle2.visibility = View.VISIBLE
                tvTitle5.visibility = View.VISIBLE
                tvTitle1.text = "人工盘点"
                tvTitle5.text = "拍照盘点"
            }
            tvTitle3.visibility = View.VISIBLE
            tvTitle4.visibility = View.GONE
        } else if (bean.inventoryType == 3 && tabIndex == 0) {
            if (bean.isCheck == 0 && status != 1) {
                tvTitle2.visibility = View.VISIBLE
                tvTitle5.visibility = View.VISIBLE
                tvTitle5.text = "拍照盘点"
            }
            tvTitle1.visibility = View.GONE
            tvTitle3.visibility = View.VISIBLE
            tvTitle4.visibility = View.GONE
        } else if (bean.inventoryType == 1 && (tabIndex == 1 || tabIndex == 3)) {
            if ( status != 1) {
                tvTitle1.visibility = View.VISIBLE
                tvTitle1.text = "人工重盘"
            }
            tvTitle2.visibility = View.GONE
            tvTitle3.visibility = View.VISIBLE
            tvTitle4.visibility = View.GONE
            tvTitle5.visibility = View.GONE
        } else if (bean.inventoryType == 2 && (tabIndex == 1 || tabIndex == 3)) {
            if ( status != 1) {
                tvTitle1.visibility = View.VISIBLE
                tvTitle5.visibility = View.VISIBLE
                tvTitle1.text = "人工重盘"
                tvTitle5.text = "拍照重盘"
            }
            tvTitle2.visibility = View.GONE
            tvTitle3.visibility = View.VISIBLE
            tvTitle4.visibility = View.GONE
        } else if (bean.inventoryType == 3 && (tabIndex == 1 || tabIndex == 3)) {
            if (status != 1) {
                tvTitle5.visibility = View.VISIBLE
                tvTitle5.text = "拍照重盘"
            }
            tvTitle1.visibility = View.GONE
            tvTitle2.visibility = View.GONE
            tvTitle3.visibility = View.VISIBLE
            tvTitle4.visibility = View.GONE
        } else if (tabIndex == 2) {
            if (status != 1) {
                tvTitle4.visibility = View.VISIBLE
            }
            tvTitle1.visibility = View.GONE
            tvTitle2.visibility = View.GONE
            tvTitle3.visibility = View.VISIBLE
            tvTitle5.visibility = View.GONE
        }
        tvTitle1.setOnClickListener { v: View? ->
            // 人工盘点
            window.dismiss()
            substitute(bean)
        }
        tvTitle2.setOnClickListener { v: View? ->
            // 盘亏
            window.dismiss()
            viewModel.markPosition = 2
            bean.status = 3
            addMark(bean, "盘亏")
        }
        tvTitle3.setOnClickListener { v: View? ->
            // 盘点说明
            window.dismiss()
            viewModel.markPosition = -1
//            bean.status = 0
            addMark(bean, "添加说明")
        }
        tvTitle4.setOnClickListener { v: View? ->
            // 盘盈资产删除
            window.dismiss()
            viewModel.markPosition = 3
            viewModel.deleteByInventoryId(bean.inventoryId, window)
        }
        tvTitle5.setOnClickListener { v: View? ->
            // 拍照盘点
            window.dismiss()
            ChoiceImgHelper.ChoiceImg(this,
                { result -> result[0]?.let { t -> viewModel.uploadHeadImg(t.compressPath) } },
                {})
        }
        window.width = ViewGroup.LayoutParams.WRAP_CONTENT
        window.height = ViewGroup.LayoutParams.WRAP_CONTENT
        window.contentView = view
        window.isFocusable = true
        window.isTouchable = true
        window.isOutsideTouchable = true
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        val contentView = window.contentView
        /*  contentView.measure(ViewUtils.makeMeasureSpec(window.getWidth()),
                ViewUtils.makeMeasureSpec(window.getHeight()));*/
        val offsetY = window.contentView.measuredHeight
        val location = IntArray(2)
        anchor.getLocationOnScreen(location)
        val x = location[0]
        val y = location[1]
        val top = SizeUtils.dp2px(38f)
        PopupWindowCompat.showAsDropDown(window, anchor, 0, 0, Gravity.END)
    }

    private fun closePop(pop: CenterPopupView) {
        pop.dismiss()
    }

    // 代盘
    private fun artificial(invenFacilityBean: InventoryAssetBean) {
        viewModel.markPosition = 4
        val binding = PopupInventoryAssetSubstituteBinding.inflate(LayoutInflater.from(context))
        val pop = BaseCenterPopup(requireContext(), binding.root, "代盘")
        binding.tvFacilityName.text = invenFacilityBean.facilityName
        binding.tvFacilityNo.text = invenFacilityBean.facilityNo
        binding.tvOrg.text = invenFacilityBean.orgName
        binding.tvLocationDesc.text = invenFacilityBean.locationDesc
        binding.butClose.setOnClickListener { closePop(pop) }
        binding.butSubmit.setOnClickListener {
            val exp = viewModel.model.getLocalUserInfo()?.nickName + "已代盘此资产"
            toSubstitute(invenFacilityBean, 1, exp, 1, pop, 1, invenFacilityBean.imgList!!)
        }
        XPopup.Builder(context).asCustom(pop).show()
    }

    // 人工盘点
    private fun substitute(invenFacilityBean: InventoryAssetBean) {
        val binding = PopupInventoryAssetArtificialBinding.inflate(LayoutInflater.from(context))
        val pop = BaseCenterPopup(requireContext(), binding.root, "人工盘点")
        binding.butClose.setOnClickListener { closePop(pop) }
        binding.butSubmit.setOnClickListener {
            if (binding.invenNormal.isChecked && binding.invenLoss.isChecked) {
                showNormalToast("请选择正常或盘亏")
                return@setOnClickListener
            } else if (!binding.invenNormal.isChecked && !binding.invenLoss.isChecked) {
                showNormalToast("请选择正常或盘亏")
                return@setOnClickListener
            }
            var isNorMal: Int? = 0
            if (binding.invenNormal.isChecked) {
                isNorMal = 1
                viewModel.markPosition = 0
            } else if (binding.invenLoss.isChecked) {
                isNorMal = 3
                viewModel.markPosition = 2
            }
            if (isNorMal == 0) {
                showNormalToast("请选择正常或盘亏")
                return@setOnClickListener
            }
            val mark = binding.etNote.text.toString()
            toSubstitute(invenFacilityBean, isNorMal, mark, 0, pop, 2, invenFacilityBean.imgList!!)
        }
        binding.invenNormal.setOnClickListener(object : View.OnClickListener {
            override fun onClick(p0: View?) {
                if (!binding.invenNormal.isChecked) {
                    binding.invenNormal.isChecked = true
                    return
                }
                binding.invenLoss.isChecked = false
            }
        })
        binding.invenLoss.setOnClickListener(object : View.OnClickListener {
            override fun onClick(p0: View?) {
                if (!binding.invenLoss.isChecked) {
                    binding.invenLoss.isChecked = true
                    return
                }
                binding.invenNormal.isChecked = false
            }
        })
        XPopup.Builder(context).asCustom(pop).show()
    }

    // 添加盘点说明
    private fun addMark(invenFacilityBean: InventoryAssetBean, title: String) {
        val binding = PopupInventoryAssetArtificialBinding.inflate(LayoutInflater.from(context))
        val pop = BaseCenterPopup(requireContext(), binding.root, title)
        var mark = ""
        if (invenFacilityBean.mark != null) {
            mark = invenFacilityBean.mark!!
        }
        binding.etNote.setText(mark)
        binding.llInvenResult.visibility = View.GONE
        binding.butClose.setOnClickListener { closePop(pop) }
        binding.butSubmit.setOnClickListener {
            val marks = binding.etNote.text.toString()
            if(title == "盘亏") {
                toSubstitute(invenFacilityBean, invenFacilityBean.status, marks, 0, pop, 2, invenFacilityBean.imgList!!)
            } else {
                addInventoryNote(invenFacilityBean, invenFacilityBean.status, marks, 0, pop, invenFacilityBean.inventoryType!!, invenFacilityBean.imgList!!)
            }
        }
        XPopup.Builder(context).asCustom(pop).show()
    }

    private fun toSubstitute(
        invenFacilityBean: InventoryAssetBean,
        status: Int?,
        explaination: String?,
        isReplace: Int?,
        pop: CenterPopupView?,
        inventoryMethod: Int,
        imgList: MutableList<FileBean>
    ) {
        viewModel.substitute(
            isReplace = isReplace,    // 是否代盘 0 否   1 是
            inventoryId = invenFacilityBean.inventoryId,
            inventoryMethod = inventoryMethod,  // 盘点方式 0 拍照   1扫码   2 人工盘
//            imgList = invenFacilityBean.imgList,
            imgList = imgList,
            status = status,
            // mark= type === 2 ? this.explaination : '',
            mark = explaination,
            planInventoryMethod = 1,
            pop = pop,
            taskId = invenFacilityBean.taskId,   // 任务id
            planInventoryMethodList = invenFacilityBean.planInventoryMethodList
        )
    }

    // 添加盘点说明 addInventoryNote
    private fun addInventoryNote(
        invenFacilityBean: InventoryAssetBean,
        status: Int?,
        explaination: String?,
        isReplace: Int?,
        pop: CenterPopupView?,
        inventoryMethod: Int,
        imgList: MutableList<FileBean>
    ) {
        viewModel.addInventoryNote(
            isReplace = isReplace,    // 是否代盘 0 否   1 是
            inventoryId = invenFacilityBean.inventoryId,
            inventoryMethod = inventoryMethod,  // 盘点方式 0 拍照   1扫码   2 人工盘
//            imgList = invenFacilityBean.imgList,
            imgList = imgList,
            status = status,
            // mark= type === 2 ? this.explaination : '',
            mark = explaination,
            planInventoryMethod = 1,
            pop = pop,
            taskId = invenFacilityBean.taskId,   // 任务id
            planInventoryMethodList = invenFacilityBean.planInventoryMethodList
        )
    }
}